package com.example.test.Lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 晓果冻
 * @version 1.0
 * @date 2022/4/12 8:36
 */
public class LruCache<K,V> extends LinkedHashMap<K,V> {
    /**
     * 容量
     */
    private int capacity;

    public LruCache(int capacity) {
        super(capacity,0.75f,true);
        this.capacity = capacity;
    }

    /**
     * 清理头结点
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        boolean b = size()>capacity;
        return size()>capacity;
    }

    public static void main(String[] args) {
        LruCache<Integer,Integer> map = new LruCache(3);
        map.put(1,1);
        map.put(2,2);
        map.put(3,3);
        //容量达到3，删除最前面的
        map.put(4,4);
        for (Map.Entry<Integer,Integer> entry:map.entrySet()){
            System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
        }
        System.out.println(map);
    }
}
